import time
from serial.tools.list_ports import  comports
from serial.tools.list_ports import  grep
import threading
import serial 
import socket 
import sys  
reload(sys)  
sys.setdefaultencoding('utf-8')  
  
IP_ADDR='192.168.10.5'

DATA_BUFFER=''
lock  = threading.Lock()


def tcpServer():  
    global DATA_BUFFER
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    sock.bind(('', 9527))   
        
    while True:  
        revcData, (remoteHost, remotePort) = sock.recvfrom(1024)  
        print("[%s:%s] connect" % (remoteHost, remotePort))    
        print "revcDatalen", len(revcData)
        lock.acquire()
        DATA_BUFFER = DATA_BUFFER + revcData
        lock.release()
    sock.close()  

# serial initialization
def mainProcess():
    global DATA_BUFFER
    #p = comports()
    p = list(grep("USB"))
    port = p[0][0]
    print port
    dev = serial.Serial(port,115200)
    debBuffer = ''
    # dev.write('I am ready\n')
    while(True):
        if len(DATA_BUFFER)!=0:
            lock.acquire()
            try:
                dev.write(DATA_BUFFER)
            finally:
                DATA_BUFFER=''
                lock.release()
        else:
            time.sleep(0.1)

if __name__ == "__main__":
    thread_=threading.Thread(target=tcpServer)  
    thread_.start() 
    while True:
        try:
            mainProcess()
        except Exception as e:
            print e   